package com.attendance.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.attendance.dao.LateRepository;
import com.attendance.entity.Late;
import com.attendance.entity.dto.LateDTO;
import com.staff.entity.Staff;


@Service
@Transactional//迟到表
public class LateService implements ILateService{

	@Autowired
	private LateRepository lateRepository;
	
	public void saveOrUpdate(Late late) {
		// TODO Auto-generated method stub
		lateRepository.save(late);
	}

	
	public void delete(Long id) {
		// TODO Auto-generated method stub
		Late late=lateRepository.findOne(id);
		if(late!=null) {
			late.setStaff(null);
			lateRepository.save(late);
			lateRepository.delete(late);
		}		
	}

	
	public void delete(List<Long> ids) {
		// TODO Auto-generated method stub
		List<Late> lateList=(List<Late>) lateRepository.findAll(ids);
		if(lateList!=null) {
			for(Late late :lateList) {
				late.setStaff(null);
				lateRepository.save(late);
			}
			lateRepository.delete(lateList);
		}

	}

	@Transactional(readOnly=true)
	public Late findOne(Long id) {
		// TODO Auto-generated method stub
		return lateRepository.findOne(id);
	}

	@Transactional(readOnly=true)
	public List<Late> findAll() {
		// TODO Auto-generated method stub
		return (List<Late>) lateRepository.findAll();
	}

	@Transactional(readOnly=true)
	public Page<Late> findAll(Specification<Late> spec, Pageable pageable) {
		// TODO Auto-generated method stub
		return lateRepository.findAll(spec, pageable);
	}


	public Page<LateDTO> findPage(String staffName, String staffNum, Pageable pageable) {
		List<LateDTO> results = new ArrayList<LateDTO>();
		List<Late> list = new ArrayList<Late>();
		if(staffName!=""&&staffName!=null) {
			list = lateRepository.findLikeStaffName(staffName);
		}else if(staffNum!=""&&staffNum!=null) {
			list = lateRepository.findLikeStaffNum(staffNum);
		}else {
			list = (List<Late>) lateRepository.findAll();
		}
		for(Late a:list) {
			Staff staff = a.getStaff();
			if(staff == null)return null;
			String dept = null;
			if(staff!=null) {
				if(staff.getDepartment()!=null)dept = staff.getDepartment().getName();
			}
			results.add(new LateDTO(staff, a, dept));
		}
		List<LateDTO> page = new ArrayList<LateDTO>();
		
		int i = pageable.getPageNumber()*pageable.getPageSize();
		int n = i+pageable.getPageSize();
		while(i<results.size()&&i<n) {
			page.add(results.get(i));
			i++;
		}
		return new PageImpl<LateDTO>(page,pageable,page.size());
	}

}
